﻿using System.Collections.Generic;
using System.IO;
using System.Text;

namespace CalcSharp.Core
{
    public class CSVParser
    {
        private List<string[]> Storage;
        private int rows;
        private int cols;
        public CSVParser(int rows, int cols)
        {
            string[] construct = new string[cols];
            Storage = new List<string[]>();

            for (int i = 0; i < rows; i++)
            {
                Storage.Add(construct);
            }

            this.rows = rows;
            this.cols = cols;
        }

        public CSVParser(Stream Input, char delim)
        {
            this.load(Input, delim);
        }

        public int Rows
        {
            get { return this.rows; }
        }

        public int Cols
        {
            get { return this.cols; }
        }

        public string this[int row, int col]
        {
            get
            {
                return this.Storage[row][col];
            }
            set
            {
                this.Storage[row][col] = value;
            }
        }

        public void save(Stream output, char delim)
        {
            StreamWriter w = new StreamWriter(output);
            StringBuilder line;
            for (int i = 0; i < this.rows; i++)
            {
                line = new StringBuilder();
                for (int j=0; j<this.Storage[i].Length; j++)
                {
                    line.Append(this.Storage[i][j]);
                    if (j != this.Storage[i].Length-1) line.Append(delim);
                }
                w.WriteLine(line.ToString());
            }
        }

        public void Clear()
        {
            this.rows = 0;
            this.cols = 0;
            for (int i = 0; i < this.Storage.Count; i++)
            {
                this.Storage[i] = null;
            }
            this.Storage = null;
        }

        public void load(Stream Input, char delim)
        {
            if (this.rows > 0 || this.cols > 0) this.Clear();
            string[] cells;
            this.Storage = new List<string[]>();
            StreamReader r = new StreamReader(Input);
            cells = r.ReadLine().Split(delim);
            this.cols = cells.Length;
            Storage.Add(cells);
            while (!r.EndOfStream)
            {
                cells = r.ReadLine().Split(delim);
                Storage.Add(cells);
            }
            this.rows = Storage.Count;
            r.Close();
        }
    }
}
